﻿using Microsoft.EntityFrameworkCore;
using Wenyu.Framework.DbModels.Entities;

namespace Wenyu.Framework.DbModels
{
    public class FrameworkDbContext:DbContext
    {
        private readonly string _connectionString;

        /// <summary>
        /// 带有书库连接字符串的参数
        /// </summary>
        /// <param name="connectionString"></param>
        public FrameworkDbContext(string connectionString) {
            this._connectionString = connectionString;
        }

        public FrameworkDbContext(DbContextOptions<FrameworkDbContext> options)
            :base(options)
        {
            
        }

        public virtual DbSet<UserEntity> UserEntities { get; set; }

        public virtual DbSet<MenuEntity> MenuEntities { get; set; }
        public virtual DbSet<RoleEntity> RoleEntities { get; set; }
        public virtual DbSet<UserRoleMapEntity> UserRoleMapEntities { get; set; }
        public virtual DbSet<RoleMenuMapEntity> RoleMenuMapEntities { get; set; }
        public virtual DbSet<SystemLog> SystemLogs { get; set; }
        
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer(this._connectionString);
            }
        }

        /// <summary>
        /// 配置数据库表映射关系
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<UserEntity>(entity =>
            {
                entity.ToTable("UserEntity")
                .HasKey(u=>u.UserId);
            });

            modelBuilder.Entity<RoleEntity>(entity =>
            {
                entity.ToTable("RoleEntity")
                .HasKey(u => u.RoleId);
            });
            modelBuilder.Entity<MenuEntity>(entity =>
            {
                entity.ToTable("MenuEntity")
                .HasKey(u => u.Id);
            });
            modelBuilder.Entity<UserRoleMapEntity>(entity =>
            {
                entity.ToTable("UserRoleMapEntity")
                .HasKey(u => u.Id);
            });
            modelBuilder.Entity<RoleMenuMapEntity>(entity =>
            {
                entity.ToTable("RoleMenuMapEntity")
                .HasKey(u => u.Id);
            });


            modelBuilder.Entity<SystemLog>(entity =>
            {
                entity.ToTable("SystemLog")
                .HasKey(u => u.Id);
            });
        }
    }
}
